/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package swingDemoEvent;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;

/**
 *
 * @author Administrator
 */

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class JListDemo2 extends JFrame {
 
     JList list1 =null;
     JList list2 = null;
     DefaultListModel model1=null;
     DefaultListModel model2=null;
     String[] s = {"美国","加拿大","法国","日本","中国","澳洲","德国","意大利","其他"};
    
     public JListDemo2(){
        
     
        
         setLayout(new GridLayout(1,2));
        
         model1 = new DataModel(1);
         list1 = new JList(model1);
         list1.setBorder(BorderFactory.createTitledBorder("国家名称"));
         MouseListener mouseListener = new MouseAdapter(){
            public void mouseClicked(MouseEvent e){
                mouseClick(e);
            }
         };
         list1.addMouseListener(mouseListener);

         model2 = new DataModel(2);
         list2 = new JList(model2);
         list2.setBorder(BorderFactory.createTitledBorder("你最喜欢得到哪个国家呢?"));
         list2.addMouseListener(mouseListener);
         add(new JScrollPane(list1));
         add(new JScrollPane(list2));
        
     }
    public void mouseClick(MouseEvent e){
int index;
        
        if (e.getSource() == list1)
        {
            if(e.getClickCount() == 2)
            {
                index = list1.locationToIndex(e.getPoint());
                String tmp = (String)model1.getElementAt(index);
                model2.addElement(tmp);
                list2.setModel(model2);
                model1.removeElementAt(index);
                list1.setModel(model1);
            }
        }
        if (e.getSource() == list2)
        {
            if(e.getClickCount() == 2)
            {
                index = list2.locationToIndex(e.getPoint());
                String tmp = (String)model2.getElementAt(index);
                model1.addElement(tmp);
                list1.setModel(model1);
                model2.removeElementAt(index);
                list2.setModel(model2);
            }
        }
        
    }
    
     class DataModel extends DefaultListModel{
         DataModel(int flag)
     {
     if (flag == 1)
     {
     for(int i=0; i < s.length; i++)
     addElement(s[i]);
     }
     }
     }
    
     public static void main(String[] args) {
            JListDemo2 ls = new JListDemo2();
            
            ls.setVisible(true);

        }

}
